package com.zy.is.common.shiro;

import cn.hutool.core.util.ObjectUtil;
import com.zy.is.domain.SysUser;
import com.zy.is.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.ByteSource.Util;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName: MyShiroRealm
 * @Description: shiro域配置
 * @Author: Yanzy
 * @Data: 2021/4/1 16:49
 * @Source: 1.0
 */
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {

    @Resource
    private SysUserService sysUserService;

    /**
     * 授权信息配置
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        return null;
    }

    /**
     * 登录认证信息
     * @param token token
     * @return 认证信息
     * @throws AuthenticationException e
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 返回认证信息, 一般为用户名
        Object principal = token.getPrincipal();
        if (ObjectUtil.isNull(principal)) {
            return null;
        }
        // 获取数据库中用户信息
        String loginName = principal.toString();
        SysUser user = sysUserService.findSysUserByName(loginName);
        if (null == user) {
            log.debug("{} - 登录用户不存在!", loginName);
            throw new UnknownAccountException("登录用户不存在!");
        }

        // 使用盐加密 构造方法
        ByteSource credentialsSalt = ByteSource.Util.bytes(loginName);;
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getLoginPwd(), credentialsSalt, getName());

        // 验证信息
        //SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getLoginPwd(), getName());
        log.debug("验证登录信息: {} ===>>>> {}", loginName, simpleAuthenticationInfo.getPrincipals());
        return simpleAuthenticationInfo;
    }
}
